import express, {Request, Response} from 'express'
import cors from 'cors'
import expressJwt from 'express-jwt'
import Log4js from './core/log/Log4jsConfig'
import {R} from './core/domain/R'
import {NotFoundMiddleware} from './core/middleware/common/NotFoundMiddleware'
import './modular/auth/controller/AuthController'
import './modular/sys/controller/SysMenuController'
import './modular/actions/controller/ActionGroupController'

import router from "./router";
import {CommonConst} from "./core/consts/CommonConst";


export const app = express()

const logger = Log4js.getLogger('app')
app.use(Log4js.connectLogger(logger, {
    level: 'info'
}))

app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(cors())

app.use(expressJwt({
    algorithms: [CommonConst.authAlgorithms],
    secret: CommonConst.authSecret,
    requestProperty: CommonConst.authRequestProperty
}).unless({
    path: [
        {url: /^\/auth\/.*/, methods: ['GET', 'POST']},
    ]
}))

app.get('/', (req: Request, res: Response) => {
    res.json(R.ok({
        id: 1001,
        title: '系统设置'
    }))
})

app.use(router)

app.use((err:any, req:any, res:any, next:any) => {
    if (err.name === 'UnauthorizedError') {
        // logger.info('req headers')
        // logger.info(req.headers)
        res.json(R.fail('invalid token'))
    }
})

app.use(NotFoundMiddleware)
